//
//  GetDataMethods.m
//  HappinessTrip
//
//  Created by dllo on 15/9/30.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "GetDataMethods.h"
#import "AFNetworking.h"

@implementation GetDataMethods

+ (void)getDataByString:(NSString *)string BodyString:(NSDictionary *)bodyDic WithDataBlock:(void(^)(id data))dataBlock
{
    
    //1.字符串的转化
    string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:string]];
    //2.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //3.设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js", nil];
    //4.开始请求
    if (!bodyDic) {
        //如果bodyDic为空就执行get请求
        [manager GET:string parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络已中断, 请检查网络设置" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
            [alertView show];
            
            NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [array lastObject];
            NSString *documentPath = [documents stringByAppendingPathComponent:@"data2.plist"];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isExist = [fileManager fileExistsAtPath:documentPath];
            if (isExist) {
                NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:documentPath];
                dataBlock(dic);
            }
            
        }];
    }
    else {
        [manager POST:string parameters:bodyDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败");
        }];
    }
    

    
    
    
    
    
    
}




















@end
